package com.lzj.common.helper;

import com.lzj.common.core.domain.model.LoginUser;
import com.lzj.common.exception.ServiceException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author 贱贱
 * @Description 安全助手 - 操作安全上下文
 * @Date 2024/07/29 16:35
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityHelper {

    /**
     * 获取用户部门ID
     */
    public static Long getDeptId() {
        return getLoginUser().getDeptId();
    }

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try
        {
            return getLoginUser().getUserId();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取用户ID异常");
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try
        {
            return getLoginUser().getUsername();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取用户账户异常");
        }
    }
    
    public static LoginUser getLoginUser() {
        try
        {
            return (LoginUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取用户信息异常");
        }
    }

    /**
     * 获取Authentication - 认证信息
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 设置Authentication - 认证信息
     */
    public static void setAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    /**
     * 认证信息 - 显式地清空认证信息 (当前线程)
     */
    public static void clearAuthentication() {
        SecurityContextHolder.clearContext();
    }

    /**
     * 是否超级管理员
     */
    public static boolean isAdmin() {
        return isAdmin(getUserId());
    }
    public static boolean isAdmin(Long userId) {
        return userId != null && userId == 1L;
    }
    
}
